package com.wnn.demo.shiro;


import com.wnn.demo.advice.MyException;
import com.wnn.demo.domain.User;
import com.wnn.demo.model.system.service.UserService;
import com.wnn.demo.pojo.ResultCode;
import com.wnn.demo.utils.MyByteSource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Map;


public class MyRealm extends AuthorizingRealm {

    @Override
    public void setName(String name) {
        super.setName("WnnRealm");
    }

    @Autowired
    private UserService userService;

    /**
     * 授权 需要权限的URL操作会进入授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //principalCollection对象就是认证info传递的数据信息，因为传递的是user对象就强转成User对象
        String username= (String) principalCollection.getPrimaryPrincipal();
        User userData = userService.findUserByName(username);
        HashSet< String > roles = new HashSet<>();
        HashSet< String > perms = new HashSet<>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List< Map<String,Object> > userById = userService.findUserById(userData.getUserId());
        if (userById.size()==0){
            return info;
        }
        for (Map< String, Object > user: userById){
            String code = (String)user.get("code");
            String role = (String)user.get("name");
            if (!"".equals(code)){
                perms.add(code);
            }else if (!"".equals(role)){
                roles.add(role);
            }
        }
        System.out.println("用户拥有的角色:"+roles);
        System.out.println("用户拥有的权限:"+perms);
        info.setRoles(roles);
        info.setStringPermissions(perms);
        return info;
    }


    /**
     * 认证 首次登录使用
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String password = new String(token.getPassword());
        if (password.isEmpty()){
            return null;
        }
        User user = userService.findUserByName(token.getUsername());

        if (user==null){
            throw new MyException(ResultCode.ERROR,"账号不存在！");
        }
        if (user.getStatus()==0){
            throw new MyException(ResultCode.ERROR,"账户异常，请联系管理员！");
        }
        //配置密码器比较 封装info 1、用户对象信息 2、数据库的加密的密码 3、byte进制的盐 4、realm的名称
        return new SimpleAuthenticationInfo(user.getUserName(), user.getUserPassword(), new MyByteSource(user.getUserName()),this.getName());

    }


    /**
     * 重写方法,清除当前用户的的 授权缓存
     * @param principals
     */
    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    /**
     * 重写方法，清除当前用户的 认证缓存
     */
    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    /**
     * 自定义方法：清除所有 授权缓存
     */
    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    /**
     * 自定义方法：清除所有 认证缓存
     */
    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    /**
     * 自定义方法：清除所有的  认证缓存  和 授权缓存
     */
    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }

}
